import { useMemo } from 'react';
import { useSplitPaths } from '.';

/**
 * @param {ResourceTree} menuTree
 * @param {String} prefix
 * @return {Resource[]}
 */
function useBreadcrumb(menuTree, { prefix = '' } = {}) {
  const paths = useSplitPaths(prefix);
  return useMemo(() => {
    const menuList = [];
    let currentMenu = { children: menuTree };
    for (let i = 0; i < paths.length; i++) {
      const url = paths[i];
      const nextMenu = (currentMenu?.children || []).find((item) => item.url === url) || null;
      if (!nextMenu) break;
      currentMenu = nextMenu;
      menuList.push(nextMenu);
    }
    return menuList;
  }, [paths, menuTree]);
}

export default useBreadcrumb;
